import { ShellUtil } from "./ShellUtil";
import { Main } from "../Main";
import { FileIoUtil } from "./FileIOUtil";

/**
 * 热更新测试切正式工具
 * @author 赵占涛
 */
export class UpdateDebug2ReleaseUtil {
    static exec(plat: string, iosOrAndroid: "ios" | "android", cb: () => void) {
        ShellUtil.exec(`
            rsync -avz ${Main.projPath}publishclient/${plat}/debug/${iosOrAndroid}/src/ ${Main.projPath}publishclient/${plat}/release/${iosOrAndroid}/src/ || exit 1
            rsync -avz ${Main.projPath}publishclient/${plat}/debug/${iosOrAndroid}/res/ ${Main.projPath}publishclient/${plat}/release/${iosOrAndroid}/res/ || exit 1
        `, () => {
            this.changeAndMoveManifest(plat, iosOrAndroid, "version", () => {
                this.changeAndMoveManifest(plat, iosOrAndroid, "project", cb);
            });
        })
    }
    private static changeAndMoveManifest(plat: string, iosOrAndroid: "ios" | "android", versionOrProject: string, cb: () => void) {
        FileIoUtil.readFile(`${Main.projPath}publishclient/${plat}/debug/${iosOrAndroid}/${versionOrProject}.manifest`, (data) => {
            let versionOrProjectObj = JSON.parse(data.toString());
            versionOrProjectObj.packageUrl = versionOrProjectObj.packageUrl.replace(`/${plat}/debug/${iosOrAndroid}/`, `/${plat}/release/${iosOrAndroid}/`);
            if (versionOrProjectObj.remoteManifestUrl) {
                versionOrProjectObj.remoteManifestUrl = versionOrProjectObj.remoteManifestUrl.replace(`/${plat}/debug/${iosOrAndroid}/`, `/${plat}/release/${iosOrAndroid}/`);
            }
            versionOrProjectObj.remoteVersionUrl = versionOrProjectObj.remoteVersionUrl.replace(`/${plat}/debug/${iosOrAndroid}/`, `/${plat}/release/${iosOrAndroid}/`);
            FileIoUtil.writeFile(`${Main.projPath}publishclient/${plat}/release/${iosOrAndroid}/${versionOrProject}.manifest`, JSON.stringify(versionOrProjectObj, undefined, 2), cb);
        })
    }
}